package self.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by hasee on 2018/1/29.
 */
public class SelfRealm extends AuthorizingRealm {

    private UserDao userDao = new UserDao();

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //用户身份信息在principalCollection
        String userName = (String) principalCollection.getPrimaryPrincipal();
        Connection conn = DbUtil.getConn();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(userDao.getRolesWithName(conn,userName));
        info.setStringPermissions(userDao.getPermissionsWithName(conn,userName));


        return info;
    }

    //验证当前登录用户，认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String userName = (String) authenticationToken.getPrincipal();

        Connection conn = DbUtil.getConn();

        User user = userDao.getUserWithName(conn,userName);

        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if(user != null){
            AuthenticationInfo info = new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),"XX");
            return info ;
        }else{

            return null;
        }

    }
}
